package me.yangbajing.web
package snippet

import scala.xml.NodeSeq

import net.liftweb.http.{S, DispatchSnippet}
import net.liftweb.util.Helpers._

import me.yangbajing.model.MTag

object TagSnippet extends DispatchSnippet {
  def dispatch = {
    case "datas" => datas
    case "detail" => detail
  }

  def detail(nodeSeq: NodeSeq): NodeSeq = {
    val cssSel =
      for {
        tag <- W.reqTag.is
      } yield {
        "@tag-id" #> tag.tag &
          "@tag-size" #> tag.size
      }

    cssSel map (_ apply nodeSeq) openOr <h1 class="text-danger">标签未不存在</h1>
  }

  def datas(nodeSeq: NodeSeq): NodeSeq = {
    val curPage = H.param("tag_page", 1)
    val limit = S.attr("tagLimit") or S.param("tag_limit") flatMap asInt openOr 500
    println(s"curPage: $curPage, limit: $limit")
    val page = MTag.pagination(curPage, limit)
    val cssSel =
      ".me-tags a" #> page.page.map {
        tag =>
          "a [href]" #> W.hrefTag(tag.tag) &
            "a [title]" #> tag.size &
            "a [style]" #> fontSize(tag.size) &
            "a [class]" #> labelColor(tag.size) &
            "a *" #> tag.tag
      }                     &
    ".pagination" #> page.pagination("", pageKey = "tag_page", limitKey = "tag_limit")

    cssSel(nodeSeq)
  }

  def fontSize(size: Int): String =
    size match {
      case i if i < 10 => "font-size:80%;"
      case i if i < 100 => "font-size:90%;"
      case i if i < 250 => "font-size:100%;"
      case i if i < 500 => "font-size:115%;"
      case i if i < 1000 => "font-size:125%;"
      case i if i < 2500 => "font-size:150%;"
      case i if i < 5000 => "font-size:165%;"
      case i if i < 7500 => "font-size:185%;"
      case _ => "font-size:200%;"
    }

  def labelColor(size: Int): String =
    size match {
      case i if i < 10 => "text-muted"
      case i if i < 50 => ""
      case i if i < 100 => "text-info"
      case i if i < 200 => "text-success"
      case i if i < 500 => "text-primary"
      case i if i < 1000 => "text-warning"
      case _ => "label-danger"
    }

}
